import React, { Component } from 'react';
import {  Pagination, message, Icon ,Modal,Checkbox,Skeleton } from 'antd';
import PropTypes from 'prop-types'
import * as API from '../../api/api';
import CommentItem from './item'
import './index.less'
const confirm = Modal.confirm;

export default class Comment extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataList: [],
            user_num:0,     //评论该文章的用户数量
            commentId: '',
            toId: '',
            isM:false,
            page:1,
            limit:5,
            total:0,
            all_count:0,
            order_by: 'timeRev',
            showControl: false,      //是否显示评论框
        }
    }
    static propTypes = {
        articleId: PropTypes.string.isRequired,
        authorId: PropTypes.string,
    }
    componentDidMount() {
        this.getComments()
        window.document.onkeydown = (event)=>{
            var e = event || window.event || arguments.callee.caller.arguments[0];
            if(e && e.keyCode==27){ // 按 Esc 
                if(this.state.showControl){
                    this.closeControl()
                }
            }
        }; 
    }

    //获取评论列表
    getComments() {
        this.setState({
            loading:true
        })
        let id = this.props.articleId;
        let params = {
            limit:this.state.limit,
            page:this.state.page,
            order_by:this.state.order_by,
        }
        API.getComments(id,params).then(res => {
            if (res.data.code === 1) {
                this.setState({
                    all_count:res.data.all_count,
                    dataList: res.data.data,
                    loading:false,
                    total: res.data.total
                })
            }
        })
    }
    onPageChange=(val)=>{
        this.setState({     //setState 可以被认为异步，
            page:val
        },()=>{
            this.getComments()
        })
    }
    openControl = () => {
        this.setState({
            showControl:true
        })
    }
    closeControl = () => {
        this.refs.content.setAttribute('placeholder','来发表一下你的看法吧')
        this.setState({
            commentId: '',
            toId: '',
            showControl:false
        })
    }
    //评论回复
    handleReply = (item,commentId) => {
        let placeholder = '回复@' + item.from.username + ' ';
        this.refs.content.setAttribute('placeholder',placeholder)
        this.setState({
            showControl:true,
            commentId: commentId,
            toId:item.from._id
        })
    }

    //发表评论
    handleSubmit = (type) => {
        let content = this.refs.content.value;
        let {articleId} = this.props;
        let {commentId,toId,isM} = this.state;
        if (!content || !content.trim().length) {
            return message.error('您忘记输入内容了');
        }
        let data = {
            commentId,
            toId,
            content
        }
        if (type === 'reply') {
            data.isM = isM;
        }
        API.submitComment(articleId, data).then(res => {
            if (res.data.code === 1) {
                message.success('发表成功');
                this.getComments();
                this.refs.content.value = '';
                this.props.updateCommentNum(this.state.all_count+1);
                this.closeControl()
            } else {
                message.error(res.data.message);
            }
        })
    }

    //点赞
    handleLike = (id) => {
        if (!id) {
            return;
        }
        API.addCommentLike(id).then(res => {
            if (res.data.code === 1) {
                if(res.data.isLike){
                    message.success('成功点赞');
                }else{
                    message.success('您已取消点赞');
                }
                var d = this.state.dataList.map((item)=>{
                    if(item._id === id){
                        item.like_count = res.data.count
                        item.isLike = res.data.isLike;
                    }else if(item.reply.length){
                        for(let i=0;i<item.reply.length;i++){
                            if(item.reply[i]._id===id){
                                item.reply[i].like_count = res.data.count
                                item.reply[i].isLike = res.data.isLike;
                                break;
                            }
                        }
                    }
                    return item;
                })
                this.setState({
                    dataList:JSON.parse(JSON.stringify(d))      //必须进行深拷贝，否则直接赋值为 d 则子组件commentItem 不会刷新
                })
            } else {
                message.error(res.data.message);
            }
        })
    }

    //删除评论
    handleRemove = (id) => {
        var ctx = this;
        if (!id) {
            return;
        }
        confirm({
            title:'确定删除吗',
            okText:'确定',
            cancelText:'取消',
            onOk(){
                 API.removeComment(id).then(res => {
                    if (res.data.code === 1) {
                        message.success('删除成功');
                        ctx.getComments()
                        ctx.props.updateCommentNum(ctx.state.all_count-1);
                    } else {
                        message.error(res.data.message);
                    }
                })
            },
            onCancel(){}
        })
       
    }

    //取消回复
    cancleReply = () => {
        this.refs.content.value = '';
        this.refs.content.setAttribute('placeholder','来发表一下你的看法吧')
        this.setState({
            commentId: '',
            toId: '',
            showControl:false
        })
    }

    onToMianChange=(e)=> {
        this.setState({
            isM:e.target.checked
        })
    }


    render() {
        let loading = this.state.loading ? this.state.loading : false;
        let {showControl,page,limit,total,dataList} = this.state;
        let {authorId} = this.props;
        let ToggleBtn=()=>{
            if (this.state.commentId.length) {
                return (
                    <div>
                        <Checkbox checked={this.state.isM} onChange={this.onToMianChange}>同时发表到主评论</Checkbox>        
                        <input type="button"  value="取消" onClick={this.cancleReply}/>
                        <input type="button" className="reply_btn" onClick={this.handleSubmit.bind(this,'reply')} value="回复" />
                    </div>
                )
            } else {
                return (
                    <input type="button" onClick={this.handleSubmit} value="提交" />
                )     
            }
        }
        return (
            <div className="comment-wrapper">
                <div className="comment_info">
                    <button type="button" className="btn btn-text" onClick={this.openControl}>回复作者</button>
                </div>    
                
                <div className={["comment_form_fixed", !showControl?"closed":'open'].join(' ')} >    
                    <div className="comment_control">
                        <a className="toggle_control" onClick={this.closeControl}>
                            <Icon type="down-circle-o" />
                        </a>    
                        <form id="comment_form" className="comment_form">
                            <div className="form-ceil form-content">
                                <div className="form-textarea">
                                    <textarea ref="content" name="content" placeholder="来发表一下你的看法吧"></textarea>
                                </div>
                                <div className="form-toolbars clearfix">
                                    <div className="form-action">
                                        <ToggleBtn />
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>    
                </div>
                <div className="comment-list-wrapper">
                    <Skeleton loading={loading} avatar active>
                        <div className="comment-area">
                            <ul className="list-unstyled">
                                {
                                    dataList.map((item) => {
                                        return (
                                            <CommentItem
                                                commentData={item}
                                                authorId={authorId}
                                                did={item._id}
                                                key={item._id}
                                                handleReply={this.handleReply}
                                                handleLike={this.handleLike}
                                                handleRemove={this.handleRemove}
                                               
                                            />
                                        )
                                    })
                                }    
                            </ul>    
                        </div>
                    </Skeleton>
                </div>
                {
                    dataList.length>0?(
                        <div className="pagination">
                            <Pagination current={page} size="middle" onChange={this.onPageChange} pageSize={limit} total={total}></Pagination>
                        </div>
                    ):''
                }
             </div>
           
        );
    }
}